package com.yanghui.dtracing.plugin.redis;

import com.yanghui.dtracing.core.constant.TypeEnum;
import com.yanghui.dtracing.core.opentracing.DTracerTags;
import com.yanghui.dtracing.core.plugin.interceptor.AbstractInstanceMethodInterceptor;
import com.yanghui.dtracing.core.plugin.interceptor.MethodInterceptResult;
import io.opentracing.Span;
import io.opentracing.tag.Tags;
import org.redisson.client.RedisConnection;
import org.redisson.client.protocol.CommandData;
import org.redisson.client.protocol.CommandsData;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class RedissonInstanceMethodInterceptor extends AbstractInstanceMethodInterceptor {

    @Override
    protected void doBeforeMethod(Object thisObj, Method method, Object[] allArguments, MethodInterceptResult result, Span span) throws Throwable {
        RedisConnection redisConnection = (RedisConnection)thisObj;
        String host = redisConnection.getRedisClient().getConfig().getAddress().getHost() + ":" +
                redisConnection.getRedisClient().getConfig().getAddress().getPort();
        Object args1 = allArguments[0];
        List<String> commandList = new ArrayList<>();
        if(args1 instanceof CommandsData){
            CommandsData commandsData = (CommandsData)args1;
            for(CommandData commandData : commandsData.getCommands()){
                commandList.add(commandData.getCommand().getName());
            }
        }else if(args1 instanceof CommandData){
            CommandData commandData = (CommandData)args1;
            commandList.add(commandData.getCommand().getName());
        }
        if(!commandList.isEmpty()){
            span.setTag(Tags.DB_STATEMENT, commandList.toString());
        }
        span.setTag(Tags.COMPONENT, DTracerTags.COMPONENT_REDISSON)
                .setTag(Tags.DB_INSTANCE,host)
                .setTag(DTracerTags.TYPE, TypeEnum.EXIT.getName());
    }
}
